package com.peng.vod.controller;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.peng.base.exception.GuliException;
import com.peng.utils.Result;
import com.peng.vod.service.VodService;
import com.peng.vod.utils.ConstantVodUtils;
import com.peng.vod.utils.InitObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/vod/video")
public class VodController {

    @Autowired
    private VodService vodService;

    //上传视频到阿里云
    @PostMapping("/uploadAliyunVideo")
    public Result uploadAliyunVideo(MultipartFile file){
        //返回上传视频的id
        String videoId = vodService.uploadVideoAliyun(file);
        return Result.ok().data(videoId);
    }

    //根据视频Id删除视频
    @DeleteMapping("/removeAliyunVideo/{id}")
    public Result removeAliyunVideo(@PathVariable String id){
        vodService.removeAliyunVideo(id);
        return Result.ok();
    }

    //根据视频Id删除视频
    @DeleteMapping("/removeBatch")
    public Result removeBatch(@RequestParam("videoIdList") List<String> videoIdList){
        vodService.removeBatch(videoIdList);
        return Result.ok();
    }

    //根据视频id获取视频凭证
    @GetMapping("/getPlayAuth/{id}")
    public Result getPlayAuth(@PathVariable String id) {
        try{
            //创建初始化对象
            DefaultAcsClient cl = InitObject.initVodClient(ConstantVodUtils.ACCESSKEY_ID,ConstantVodUtils.ACCESSKEY_SECRET);
            //创建获取视频地址request对象和response对象
            GetVideoPlayAuthRequest request = new GetVideoPlayAuthRequest();
            //向request对象设置视频id值
            request.setVideoId(id);
            GetVideoPlayAuthResponse response = cl.getAcsResponse(request);
            //获取视频播放凭证
            String playAuth = response.getPlayAuth();
            return Result.ok().data(playAuth);
        }catch (Exception e){
            e.printStackTrace();
            throw  new GuliException(20001,"获取失败");
        }
    }
}
